import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@kernelproxy/ui';
import { useLanguage, useLocalizedLink } from '@kernelproxy/i18n';
import { authService } from '../services/auth';
import { Shield } from 'lucide-react';

const MFAVerify = () => {
  const [otp, setOtp] = useState('');
  const [challengeId, setChallengeId] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const navigate = useNavigate();
  const { language } = useLanguage();
  const { getLink } = useLocalizedLink();

  useEffect(() => {
    // Create MFA challenge on component mount
    createChallenge();
  }, []);

  const createChallenge = async () => {
    try {
      const result = await authService.createMFAChallenge('totp');
      if (result.success && result.challenge) {
        setChallengeId(result.challenge.$id);
      } else {
        setError(language === 'zh-CN' ? '无法创建MFA挑战' : 'Failed to create MFA challenge');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '无法创建MFA挑战' : 'Failed to create MFA challenge');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!otp || otp.length !== 6) {
      setError(language === 'zh-CN' ? '请输入6位验证码' : 'Please enter 6-digit code');
      return;
    }

    if (!challengeId) {
      setError(language === 'zh-CN' ? '无效的MFA会话' : 'Invalid MFA session');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const result = await authService.completeMFAChallenge(challengeId, otp);
      if (result.success) {
        // MFA verification successful, redirect to dashboard
        navigate(getLink('/dashboard'));
      } else {
        setError(language === 'zh-CN' ? '验证码无效或已过期' : 'Invalid or expired verification code');
        setOtp('');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '验证失败，请重试' : 'Verification failed, please try again');
      setOtp('');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    navigate(getLink('/login'));
  };

  return (
    <div className="h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4 transition-colors duration-300">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-[#00d4ff]/10 rounded-full mb-4">
            <Shield className="w-8 h-8 text-[#00d4ff]" />
          </div>
          <h2 className="text-3xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '双因素认证' : 'Two-Factor Authentication'}
          </h2>
          <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
            {language === 'zh-CN' 
              ? '请输入您的认证应用中显示的6位验证码' 
              : 'Enter the 6-digit code from your authenticator app'}
          </p>
        </div>

        <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow-lg sm:rounded-lg sm:px-10 transition-colors duration-300">
          {error && (
            <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            </div>
          )}

          <form className="space-y-6" onSubmit={handleSubmit}>
            <div>
              <label htmlFor="otp" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                {language === 'zh-CN' ? '验证码' : 'Verification Code'}
              </label>
              <input
                id="otp"
                type="text"
                value={otp}
                onChange={e => setOtp(e.target.value.replace(/\D/g, '').slice(0, 6))}
                maxLength={6}
                placeholder="000000"
                autoFocus
                className="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] text-center text-2xl tracking-widest font-mono"
              />
            </div>

            <div className="space-y-3">
              <Button type="submit" fullWidth variant="gradient" disabled={loading || otp.length !== 6}>
                {loading 
                  ? (language === 'zh-CN' ? '验证中...' : 'Verifying...') 
                  : (language === 'zh-CN' ? '验证' : 'Verify')}
              </Button>

              <Button type="button" onClick={handleCancel} fullWidth variant="outline">
                {language === 'zh-CN' ? '取消' : 'Cancel'}
              </Button>
            </div>
          </form>

          <div className="mt-6 text-center">
            <p className="text-xs text-gray-500 dark:text-gray-400">
              {language === 'zh-CN' ? '无法访问认证应用？' : 'Can\'t access your authenticator?'}
              <br />
              <button 
                type="button"
                className="text-[#00d4ff] hover:underline mt-1"
                onClick={() => alert(language === 'zh-CN' ? '请联系管理员' : 'Please contact administrator')}
              >
                {language === 'zh-CN' ? '使用恢复代码' : 'Use recovery code'}
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MFAVerify;
